<template>
  <!-- 上传图片组件 -->
  <div>
    <ImageShow
      :value.sync="fileList"
      isEdit
      :onlyShow="$attrs.onlyShow"
      :readonly="readonly || disabled"
      style="margin-top: 10px"
      @change="handleChange"
    >
      <li
        class="form-components form-image-show--item"
        v-if="!$attrs.onlyShow&&fileList.length !==limit"
        style="border:none"
      >
        <div v-if="disabled" class="form-disabled" style="width: 148px"></div>
        <div v-if="readonly" class="form-readonly"></div>
        <el-upload
          accept="image/*"
          action="#"
          :multiple="multiple"
          :name="name"
          :limit="limit"
          :http-request="uploadFile"
          :show-file-list="false"
          list-type="picture-card"
          :style="newStyle"
        >
          <!-- <i class="el-icon-plus"></i> -->
          <el-icon><Plus /></el-icon>
        </el-upload>
      </li>
    </ImageShow>
    <div
      class="Fg-upload-tips"
      v-if="__config__.showTip && !$attrs.onlyShow"
      :style="newStyle.font"
    >*{{ tips }}</div>
  </div>
</template>

<script>
import ImageShow from "../components/imageShow";
import { getBase64 } from "../../../utils";
import { comMixin } from "../../../utils/comMixins";
import { requestPost2 } from "@/api/data";

export default {
  mixins: [comMixin],
  name: "form-image",
  components: {
    ImageShow,
  },
  props: {
    // 绑定的输入值
    modelValue: {
      type: [String, Number],
      default: "",
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 表单属性
    __config__: {
      type: Object,
      default: () => {},
    },

    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 	上传的文件字段名
    name: {
      type: String,
      default: "",
    },

    // 最大允许上传个数
    limit: {
      type: Number,
      default: 10,
    },
    // 文件类型
    accept: {
      type: String,
      default: "",
    },
    // 文件上传地址
    action: {
      type: String,
      default: "",
    },
    // 是否为接口上传
    isUpload: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return { fileList: [], loading: false };
  },
  watch: {
    modelValue: {
      immediate: true,
      deep: true,
      handler: function (nd, od) {
        try {
          // 回显
          this.fileList = JSON.parse(nd) || [];
        } catch (error) {
          console.log("error", error);
        }
      },
    },
  },
  computed: {
    tips() {
      // 最大上传文件+单位
      const sizeUnit = this.__config__.fileSize + this.__config__.sizeUnit;
      return `只能上传不超过${sizeUnit}的图片${this.$attrs.remark || ""}`;
    },
  },
  methods: {
    // 文件超出个数限制时的钩子
    onExceed() {
      this.$message({
        message: `最多允许上传${this.limit}张图片`,
        type: "info",
      });
    },
    validate(file) {
      // 实际上传的文件大小单位为B，需要将文件大小限制的单位转换为B
      const fileSize = this.__config__.fileSize; // 文件大小
      const fileUnit = this.__config__.sizeUnit; // 文件单位
      // 实际上传的文件大小单位为B，需要将文件大小限制的单位转换为B
      const maxSize =
        fileSize *
        { KB: 1024, MB: Math.pow(1024, 2), GB: Math.pow(1024, 3) }[fileUnit];
      let isLt = file.size < maxSize; // 判断是否超过文件大小
      if (!isLt) {
        this.$message({ message: this.tips, type: "info" });
        return false;
      } else {
        return true;
      }
    },
    async httpRequest(file) {
      if (!this.validate(file)) return;
      const url = await getBase64(file.raw);
      this.fileList.push({ name: file.name, url });
      this.handleChange(this.fileList);
    },

    // 自定义文件上传
    uploadFile(file) {
      let formData = new FormData();
      if (Array.isArray(file)) {
        // 选择多个文件
        file.forEach((item) => {
          formData.append(this.name, item.file);
        });
      } else {
        // 选择单个文件
        formData.append(this.name, file.file);
      }
      this.loading = true;
      requestPost2(this.action, formData)
        .then((res) => {
          // 只能上传一个文件，将原文件清空再添加
          if (!this.multiple) {
            this.fileList = [];
          }
          this.onSuccess(res);
        })
        .catch((err) => {
          this.onError(err);
        });
    },
    // 上传成功
    onSuccess(res) {
      if (res.code == 1) {
        try {
          res.result['mfilePath' || "mFilePath"].forEach((path, index) => {
            this.fileList.push({
              id: res.result.idList? res.result.idList[index]: index,
              name: res.result["mfileName" || "mFileName"][index],
              url: window.location.origin + path,
            });
          });
          this.handleChange(this.fileList);
          this.$message({
            message: `上传成功！`,
            type: "success",
          });
          this.loading = false;
        } catch (error) {
          console.log(error);
          this.onError(error);
        }
      } else {
        this.onError(res);
      }
    },
    // 上传失败
    onError(err) {
      this.$message({
        message: err.msg || `上传失败！`,
        type: "error",
      });
      this.loading = false;
    },

    handleChange(fileArr) {
      const value = fileArr.length ? JSON.stringify(fileArr) : null;
      this.$emit("input", value);
      this.$emit("update:modelValue", value);
      this.$emit("change", value);
      this.onChange(value);
    },
  },
};
</script>

<style lang="scss">
.form-image-show--item {
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
  }
}
</style>
